import { Viewer } from 'cesium'
import { getViewer, defaultConfig } from '@/cesium'

const eventMap: WeakMap<Viewer, Set<Function>> = new WeakMap()

function setEventMapByViewer(viewer: Viewer, fn: Function) {
  if (!eventMap.has(viewer)) {
    eventMap.set(viewer, new Set())
  }
  eventMap.get(viewer)!.add(fn)
}

type LeftClick = (e: MouseEvent) => boolean

export function onLeftClick(
  fn: Function,
  opt: { viewer?: string | Viewer } = {}
) {
  const { viewer } = opt
  if (!viewer) {
    const viewer = getViewer(defaultConfig.DEFAULT_NAME)
    if (!viewer) {
      return false
    }
    setEventMapByViewer(viewer, fn)
  }

  if (typeof viewer === 'string') {
    const _viewer = getViewer(viewer)
    if (!_viewer) {
      return
    }
    setEventMapByViewer(_viewer, fn)
  }

  if (viewer instanceof Viewer) {
    setEventMapByViewer(viewer, fn)
  }
}
